package com.easy.component.webview;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.easy.component.R;
import com.easy.component.component.header.EasyHeaderBuilder;
import com.easy.component.ibase.EasyBaseActivity;
import com.easy.component.utils.StringUtils;

/**
 * webview
 */
public class WebViewActivity extends EasyBaseActivity {

    private final static String TAG = WebViewActivity.class.getName();
    /**
     * 标题
     */
    public static final String KEY_TITLE = "title";
    /**
     * url地址
     */
    public static final String KEY_URL = "url";
    /**
     *
     */
    private EasyHeaderBuilder easyHeaderBuilder;
    /**
     * webview
     */
    private WebView mWebView;
    /**
     * WebView进度条
     */
    private ProgressBar mProgressBar;
    /**
     * url
     */
    private String mUrl;
    /**
     * 标题
     */
    private String mTitle;

    @Override
    public void initlayoutResID() {
        setContentView(R.layout.activity_webview);
    }

    @Override
    public void initBundle() {
        mTitle = getIntent().getStringExtra(KEY_TITLE);
        mUrl = getIntent().getStringExtra(KEY_URL);
    }

    @Override
    public void initView() {
        mWebView = findViewById(R.id.base_web_view);
        mProgressBar = findViewById(R.id.base_progress_bar);
        this.mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
        this.mWebView.setWebChromeClient(mChromeClient);
        this.mWebView.setWebViewClient(mWebViewClient);
        this.mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        this.mWebView.getSettings().setJavaScriptEnabled(true);
        this.mWebView.getSettings().setSaveFormData(true);
        this.mWebView.getSettings().setLoadsImagesAutomatically(true);
        this.mWebView.getSettings().setSupportZoom(false);
        this.mWebView.getSettings().setBuiltInZoomControls(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            this.mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //增加缓存
        this.mWebView.getSettings().setDomStorageEnabled(true);
        this.mWebView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        this.mWebView.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath());
        this.mWebView.getSettings().setAllowFileAccess(true);
        this.mWebView.getSettings().setAppCacheEnabled(true);
        this.mWebView.requestFocusFromTouch();
        this.mWebView.requestFocus();
    }

    @Override
    public void initHeader() {
        easyHeaderBuilder = new EasyHeaderBuilder(this);
        easyHeaderBuilder.addLeftImageBackView();
        easyHeaderBuilder.setTitle(mTitle);
        easyHeaderBuilder.addLeftImageBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishActivity();
            }
        });
    }

    @Override
    public void initLoadingView() {

    }

    @Override
    public void initData() {
        loadUrl(mUrl);
    }


    private WebChromeClient mChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int progress) {
            mProgressBar.setProgress(progress);
            super.onProgressChanged(view, progress);
            mProgressBar.setProgress(progress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            showAlert(message, "确定", new OnClickListener() {
                @Override
                public void onClick(View v) {
                    result.confirm();
                }
            });
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            showAlert(message, new OnClickListener() {
                @Override
                public void onClick(View v) {
                    result.cancel();
                }
            }, new OnClickListener() {
                @Override
                public void onClick(View v) {
                    result.confirm();
                }
            });
            return true;
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
                                  final JsPromptResult result) {
            showAlert(message, new OnClickListener() {
                @Override
                public void onClick(View v) {
                    result.cancel();
                }
            }, new OnClickListener() {
                @Override
                public void onClick(View v) {
                    result.confirm();
                }
            });
            return true;
        }
    };

    private WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            return false;
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            super.doUpdateVisitedHistory(view, url, isReload);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mProgressBar.setVisibility(View.VISIBLE);
            mProgressBar.setProgress(0);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mProgressBar.setVisibility(View.GONE);
            String title = StringUtils.clearNull(view.getTitle());
            easyHeaderBuilder.setTitle(title);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            mProgressBar.setVisibility(View.GONE);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }
    };

    /**
     * description 加载网页地址
     * version
     * date 2018/3/23
     * author 15050517
     */
    public void loadUrl(final String url) {
        mWebView.loadUrl(url);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        closeKeyboard();
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView != null && mWebView.canGoBack()) {
            goBack();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishActivity();
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 功能描述: <br>
     * 〈刷新〉
     *
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private void refresh() {
        if (mWebView != null) {
            mWebView.stopLoading();
            mWebView.clearView();
            if (mProgressBar != null && mProgressBar.getVisibility() == View.VISIBLE) {
                mProgressBar.setVisibility(View.GONE);
            }
            mWebView.reload();
        }
    }

    /**
     * 功能描述: <br>
     * 〈回退〉
     *
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private void goBack() {
        mWebView.goBack();
    }

    /**
     * 隐藏软键盘
     **/
    public void closeKeyboard() {
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }
}
